import os
import time
from datetime import datetime

from PIL import Image
# 显示结果
# qt界面相关库
from PyQt5.QtCore import QThread, pyqtSignal

from Cover import Cover
from HousePlan import HousePlan
from base.ocr_base_tool import convert_pdf_to_jpg_and_collect_paths, create_directory_if_not_exists, \
    get_error_file_name_and_line_number


# 使用示例


class MainCheckQThread(QThread):
    # timeout 是一个信号（pyqtSignal），它是 PyQt 库中用来在线程之间进行通信的一种机制。在 PyQt 中，QThread 是用来创建和管理线程的类，
    # 而 pyqtSignal 则允许线程之间发送消息。
    # timeout 信号在这里的作用可能是用来通知其他组件或线程，当前线程（myWork）已经运行了一定时间或者达到了某个特定的条件。当需要发送这样的通
    # 知时，可以在 myWork 类的某个方法中触发这个信号
    timeout = pyqtSignal(str)

    def __init__(self):
        super(MainCheckQThread, self).__init__()
        self.working = True
        self._input_path = None
        self._output_path = None

    # 设置输入和输出目录
    def set_work_directories(self, input_path, output_path):
        self._input_path = input_path
        self._output_path = output_path

    def set_working(self, is_working):
        self.working = is_working

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        while self.working:
            start_time = time.time()  # 记录开始时间

            # 1) 找到封面文件夹和图片
            self.timeout.emit(
                "现在是：{}，开始在输入目录中搜索封面文件夹和分户图pdf，请耐心等待！".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))

            self.PrepareWorkPaths()

            cover_dir = os.path.join(self._input_path, '封面')
            # 获取封面文件夹内的所有封面图片
            cover_image_path_list = [os.path.join(cover_dir, f) for f in os.listdir(cover_dir) if
                                     f.endswith(('jpg', 'png'))]
            cover_image_count = len(cover_image_path_list)
            if cover_image_count < 1:
                message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}：输入目录中没有合适的文件！请确认输入目录是否有误！"
                self.timeout.emit(message)
                print(message)
                # break

            # 2) 识别封面图片
            print("2) 识别封面图片 #####################################################################################")
            message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:一共有{cover_image_count}个文件，开始在逐个识别登记字号和坐落！"
            self.timeout.emit(message)
            print(message)

            cover_list = []

            target_dictionary = dict()
            for index, image_path in enumerate(cover_image_path_list):
                try:
                    cover = Cover(output_path=self._output_path)
                    cover.recognize_cover(image_path)
                    cover_list.append(cover)
                    message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:一共有{cover_image_count}个文件，第{index + 1}个的登记字号为：{cover.registration_number}，坐落为：{cover.address}！"
                    target_dictionary[cover.address] = cover.registration_number
                    self.timeout.emit(message)
                    print(message)

                except Exception as e:
                    message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:第{index + 1}个识别封面图片出错了： {image_path}，错误提示信息：{e},位置：{get_error_file_name_and_line_number(e)}!"
                    self.timeout.emit(message)
                    print(message)

            # 3) 拆分PDF为JPG

            message = "3) 正在拆分PDF为JPG，请耐心等待######################################################################"
            print(message)
            self.timeout.emit(message)
            page_images_list = convert_pdf_to_jpg_and_collect_paths(self._input_path,
                                                                    self._input_path + r'\temp_house_plan')
            house_plan_pages_count = len(page_images_list)
            message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:一共有{house_plan_pages_count}个文件，开始在逐个识别分户图的座落！"
            self.timeout.emit(message)
            print(message)

            # 4) 识别分户图图片
            print("4) 识别分户图图片 #####################################################################################")
            house_plans = []
            for index, image_path in enumerate(page_images_list):
                try:
                    house_plan = HousePlan(self._output_path)
                    house_plan.recognize(image_path)
                    house_plans.append(house_plan)

                    message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:一共有{house_plan_pages_count}个文件，第{index + 1}个的座落为：{house_plan.address}！"
                    self.timeout.emit(message)
                    print(message)

                except Exception as e:
                    message = f"识别分户图出错： {image_path}，提示信息: {e},位置：{get_error_file_name_and_line_number(e)}!"
                    self.timeout.emit(message)
                    print(message)

            # 5) 匹配坐落并处理输出
            print("5) 匹配坐落并处理输出 #############################################################################")
            for index, house_plan in enumerate(house_plans):
                try:
                    if house_plan.address in target_dictionary:
                        registration_number = target_dictionary[house_plan.address]
                        output_folder = os.path.join(self._output_path + r'/分户图（按登记字号存放）', registration_number, r'附图')
                        if not os.path.exists(output_folder):
                            os.makedirs(output_folder)
                        output_image_path = os.path.join(output_folder, '附图0001.jpg')
                        # 假设house_plan包含获取分户图JPG文件路径的方法
                        with Image.open(house_plan.image_path) as img:
                            img.save(output_image_path)
                        message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:一共有{house_plan_pages_count}个分户图文件，第{index + 1}个的座落为：{house_plan.address},其分户图已经放至在{registration_number}文件夹下！"
                        self.timeout.emit(message)
                        print(message)
                    else:
                        message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:一共有{house_plan_pages_count}个分户图文件，第{index + 1}个的座落为：{house_plan.address},其找到对应的登记字号！"
                        self.timeout.emit(message)
                        print(message)
                except Exception as e:
                    message = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:匹配地址错误，错误提示：{e},位置：{get_error_file_name_and_line_number(e)}!"
                    self.timeout.emit(message)
                    print(message)
                    continue  # 假设一个封面只匹配一个分户图

            self.timeout.emit("{}：结束了".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))

            # 计算并显示用时
            self.calculate_processed_time_and_show(start_time)
            # 结束
            self.working = False

    def calculate_processed_time_and_show(self, start_time):
        end_time = time.time()
        elapsed_time = end_time - start_time

        # 计算年、月、日、小时、分钟和秒
        years = int(elapsed_time // 31536000)  # 使用 int 确保结果是整数
        elapsed_time %= 31536000
        months = int(elapsed_time // 2592000)
        elapsed_time %= 2592000
        days = int(elapsed_time // 86400)
        elapsed_time %= 86400
        hours = int(elapsed_time // 3600)
        elapsed_time %= 3600
        minutes = int(elapsed_time // 60)
        seconds = round(elapsed_time % 60, 2)  # 保留两位小数

        # 格式化输出，只包含非零的部分
        formatted_parts = []
        if years:
            formatted_parts.append(f"{years} 年")
        if months:
            formatted_parts.append(f"{months} 月")
        if days:
            formatted_parts.append(f"{days} 天")
        if hours:
            formatted_parts.append(f"{hours} 时")
        if minutes:
            formatted_parts.append(f"{minutes} 分")
        if seconds > 0 or not formatted_parts:  # 确保至少显示秒，如果其他部分都是0
            formatted_parts.append(f"{seconds:.2f} 秒")

        formatted_elapsed_time = ", ".join(formatted_parts)
        self.timeout.emit(f"结束，用时：{formatted_elapsed_time}")

    def PrepareWorkPaths(self):
        # 当前目录下创建文件夹保存成功处理完毕的输入文件
        destination_folder_path = os.path.join(self._output_path, r'分户图（按登记字号存放）')
        finished_cover_path = os.path.join(self._output_path, r'finished_cover')
        finished_house_plan_path = os.path.join(self._output_path, r'finished_house_plan')
        problem_cover_path = os.path.join(self._output_path, r'problem_cover')
        problem_house_plan_path = os.path.join(self._output_path, r'problem_house_plan')
        temp_house_plan_path = os.path.join(self._output_path, r'temp_house_plan')

        # 当前目录下创建文件夹保存OCR日志
        ocr_log_folder_path = os.path.dirname(self._output_path) + r'\\ocr_log'

        # 如果不存在这三个文件夹则创建它们
        create_directory_if_not_exists(destination_folder_path)
        create_directory_if_not_exists(finished_cover_path)
        create_directory_if_not_exists(finished_house_plan_path)
        create_directory_if_not_exists(problem_cover_path)
        create_directory_if_not_exists(problem_house_plan_path)
        create_directory_if_not_exists(temp_house_plan_path)
        create_directory_if_not_exists(ocr_log_folder_path)
